package com.yearner.reviewplan.common.util;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author pengyg
 * @since 2019/10/16
 */
@Component
public class MyJdbcUtil {
    private final Environment environment;
    private Connection connection;
    private DataSource dataSource;
    private static MyJdbcUtil myJdbcUtil = null;


    public MyJdbcUtil(Environment environment) {
        this.environment = environment;
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(environment.getProperty("spring.datasource.url"));
        druidDataSource.setDriverClassName(environment.getProperty("spring.datasource.driverClassName"));
        druidDataSource.setUsername(environment.getProperty("spring.datasource.username"));
        druidDataSource.setPassword(environment.getProperty("spring.datasource.password"));
        dataSource = druidDataSource;
        myJdbcUtil = this;
    }

    public static MyJdbcUtil getInstance() {
        return myJdbcUtil;
    }
    public  DataSource getDataSource() {
        return this.dataSource;
    }
    public static DataSource sGetDataSource() {
        return getInstance().dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return getInstance().dataSource.getConnection();
    }

    public Connection beginTransactional() throws SQLException {
        connection = MyJdbcUtil.getConnection();
        if (connection == null) {
            throw new SQLException("connection获取失败");
        }
        connection.setAutoCommit(false);
        return connection;
    }

    public void commit() throws SQLException {
        if (connection != null) {
            connection.commit();
            connection.setAutoCommit(true);
            connection = null;
        }
    }

    public void rollback() {
        if (connection != null) {
            try {
                connection.rollback();
                connection.setAutoCommit(true);
                connection=null;
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

    }
}
